<template>
    <div class="app-container">
        <el-row :gutter="10" class="mb8">
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleEditPath"
                >赠送积分</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    style="float: right; padding: 3px 0"
                    type="text"
                    icon="el-icon-refresh-right"
                    @click="getList()"
                >刷新</el-button>
            </el-col>
        </el-row>

        <el-table v-loading="listLoading" :data="list" border fit highlight-current-row>
            <el-table-column align="center" label="序号">
                <template slot-scope="{row}">
                    <span>{{ row.id }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="被赠区片">
                <template slot-scope="scope">{{ scope.row.community ? scope.row.community.title : ""}}</template>
            </el-table-column>
            <el-table-column align="center" label="标题" prop="title"/>
            <el-table-column align="center" label="总积分">
                <template slot-scope="scope">{{ scope.row.score }}</template>
            </el-table-column>
            <el-table-column align="center" label="积分分成比例">
                <template slot-scope="scope">{{ scope.row.proportion }}</template>
            </el-table-column>
            <el-table-column align="center" label="积分分成">
                <template slot-scope="scope">{{ scope.row.score_proportion }}</template>
            </el-table-column>
            <el-table-column align="center" label="赠送时间">
                <template slot-scope="{ row }">
                    {{ row.gift_time | parseTime("{y}-{m}-{d}") }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="状态">
                <template slot-scope="scope">
                    <div class="color-success">已赠送</div>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作"  >
                <template slot-scope="{row}">
                    <el-button type="text" icon="el-icon-edit" @click="handleDetail(row)"> 查看 </el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.page"
            :limit.sync="queryParams.limit"
            @pagination="getList"
        />
        <el-dialog  :title="titleDetails" :visible.sync="dialogVisible" width="1000px"  >
            <el-form ref="form" :model="IntegralForm" label-width="100px">
                <el-row>
                    <el-col :span="6" >
                        <el-form-item label="时间" >
                            {{IntegralForm.time}}
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" >
                        <el-form-item label="当前总积分" >
                            {{IntegralForm.score}}
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-table  ref="Integral"  border  size="small" :data="waterIntegralDetails">

                <el-table-column show-overflow-tooltip prop="title" label="记录名称" align="center"/>
                <el-table-column align="center" label="水机名称">
                    <template slot-scope="{row}">
                        {{ row.water_device_info? row.water_device_info.water_title : "" }}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="姓名">
                    <template slot-scope="{row}">
                        {{ row.user_info? row.user_info.nickname : "" }}
                    </template>
                </el-table-column>
                <el-table-column  align="center" prop="sum_score" label="总积分" />
                <el-table-column  align="center" prop="proportion" label="赠送积分比例" />
                <el-table-column  align="center" prop="proportion" label="积分比例" />
                <el-table-column align="score" label="score_proportion">
                    <template slot-scope="{row}">
                        {{ formatNumber(row.score_proportion) }}
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script>
//引入对应的接口js文件
import { getAllCom } from "@/api/grzq/community.js";
import { getUserApparatusAllList } from "@/api/grzq/apparatus.js";
import {getScoreDetailsList,getScoreList, createScore} from "@/api/grzq/buy_scores.js";
import {parseTime, getFormatDate, deepClone} from '@/utils/index';

export default {

    dicts:['sys_user_water_role'],
    data() {
        return {
            showSearch:true,
            titleDetails:"赠送积分明细",
            communityList: [],
            userSelectList: [],
            listLoading: true,
            elementLoadingText: '正在加载...',
            queryParams: {
                page: 1,
                limit: 10,
            },
            total: 0,
            dialogVisible: false,
            list: [], //列表数据
            form: {},
            rules: {
                score: [{ required: true, message: "请输入赠送积分", trigger: "change" }],
            },
            IntegralForm:{
                score:0,
                time:""
            },
            waterIntegralDetails: [],
            waterMachineData: [],
            junDadialogVisible: false,
        };
    },

    async created() {
        await this.getList();
    },
    methods: {
        formatNumber(value) {
            return value.toFixed(3);
        },
        reset() {
            // 表单
            this.form = {
                user_id: '',
                community_id: '',
                score: 0,
                proportion: 0,
                waterMachineData: [],
            };
            this.resetForm('form')
        },
        //获取列表
        async getList() {
            let that = this;
            const {data, status, msg} = await getScoreList(that.queryParams);
            that.list = data.data;
            that.listLoading = false;
            that.total = data.total;
            that.queryParams.limit = data.per_page || 10;
        },

        // 片区
        async getAllCom() {
            const res = await getAllCom();
            this.communityList = res.data;
        },
        /** 提交按钮 */
        submitForm: function () {
            let that = this;
            that.form.waterMachineData = that.waterMachineData
            console.log("that.form", that.form)
            this.$refs['form'].validate(async valid => {
                if (valid) {
                    const {msg, status} = await createScore(that.form)
                    switch (status) {
                        case 1:
                            await that.getList();
                            that.msgSuccess('赠送成功')
                            that.dialogVisible =false;
                            that.waterMachineData=[];
                            that.reset()
                            break;
                        default:
                            that.msgError(msg);
                            this.msg
                    }
                }
            })
        },

        handleEditPath(row) {
            this.$router.push({
                'path':`/member/buyScores`
            });
        },
        handleDetail(row){
            let that = this;
            that.dialogVisible = true;
            that.checkStrictly = true;
            let gift_time = parseTime(row.gift_time,"{y}-{m}-{d}");
            let title = row.community ? row.community.title +" 时间-- "+gift_time: "";
            that.IntegralForm.time = gift_time;
            let score = row.score ;
            that.titleDetails = '赠送积分明细（'+title+'）'
            that.IntegralForm.score =0;
            getScoreDetailsList({'gift_id':row.id}).then(res=>{
                const {data} = res
                that.waterIntegralDetails = data;
                console.log(res.data);
                data.forEach((item) => {
                    //遍历prodAllPrice这个字段，并累加
                    that.IntegralForm.score =  that.IntegralForm.score += item.score;
                })
            })

        },

        async changeUserWaterMachine(userId) {
            console.log(userId)
            const {data} = await getUserApparatusAllList({userId: userId});
            this.waterMachineData = data;
        },
        calculateRatioProportion() {
            const {score, proportion} = this.form;
            // 计算每个项目的值
            this.waterMachineData = this.waterMachineData.map(item => ({
                ...item,
                proportion: proportion,// 根据分数和比例计算值
                score: (item.sum_score * (proportion / 100)).toFixed(3) // 根据分数和比例计算值
            }));
            this.form.score = this.totalScore()
            console.log(" this.form.score ", this.form.score)
        },
        calculateRow(row) {
            row.score = (row.sum_score * (row.proportion / 100)).toFixed(3);
            this.form.score = this.totalScore()
        },
        totalScore() {
            return this.waterMachineData.reduce((sum, row) => {
                return parseFloat(sum) + parseFloat(row.sum_score);
            }, 0);
        },
    },
    mounted() {

    },
    destroyed() {

    },
};
</script>

<style scoped lang="scss">

</style>
